package com.example.demo.tool;

import java.util.HashMap;
import java.util.Map;

//-- 统一返回格式
public class Result {

    //-- 内部枚举定义响应的状态码
    private enum ResultCode{
        SUCCESS("成功",200),ERROR("失败",300);
        private String msg;
        private Integer code;
        private ResultCode(String msg,Integer code){
            this.msg =msg;
            this.code =code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        @Override
        public String toString() {
            return "ResultCode{" +
                    "msg='" + msg + '\'' +
                    ", code=" + code +
                    '}';
        }
    }

    /*
        约定：后端返回给前段的格式如下
            {
                "success":true 布尔值 表示响应是否成功
                "code": 数值
                "message"：返回的消息
                "data":HashMap 返回的具体数据
            }
     */
    //-- 链式的写法 （）。（）。（）。（）。
    private boolean success;
    private Integer code;
    private String message;
    private Map<String,Object> data = new HashMap<>();

    private Result(){}

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    public static Result ok(){
        Result r = new Result();
        r.setSuccess(true);
        r.setMessage(ResultCode.SUCCESS.getMsg());
        r.setCode(ResultCode.SUCCESS.getCode());
        return r;
    }

    public static Result error(){
        Result r = new Result();
        r.setSuccess(false);
        r.setMessage(ResultCode.ERROR.getMsg());
        r.setCode(ResultCode.ERROR.getCode());
        return r;
    }

    public Result success(boolean success){
        this.setSuccess(success);
        return this;
    }

    public Result code(Integer code){
        this.setCode(code);
        return this;
    }

    public Result message(String message){
        this.setMessage(message);
        return this;
    }

    public Result data(String key,Object value){
        this.data.put(key,value);
        return this;
    }

    public Result data(Map<String,Object> map){
        this.setData(map);
        return this;
    }

}
